<template>
  <el-dialog v-model="dialogVisible" :title="bannerForm.id ? '编辑轮播图' : '新增轮播图'" width="30%">
    <el-form ref="formRef" :model="bannerForm" :rules="rules" label-width="100px" style="padding-right: 30px">
      <el-form-item label="图片:" prop="imgUrl">
        <ImgUpload @sendImage="sendImage" :initialImage="bannerForm.imgUrl" />
      </el-form-item>
      <el-form-item label="分发站点：" prop="distributionSite">
        <el-input v-model="bannerForm.distributionSite"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addBannerAPI, editBannerAPI } from "@/apis/banner.js";
import ImgUpload from "@/components/ImageUpload/index.vue";

// 状态和引用定义
const dialogVisible = ref(false);
const formRef = ref(null);
const bannerForm = ref({
  imgUrl: "",
  distributionSite: "",
});

// 表单验证规则
const rules = {
  imgUrl: [
    { required: true, message: "图片不能为空", trigger: "blur" },
  ],
  distributionSite: [{ required: true, message: "分发站点不能为空", trigger: "blur" }],
};

// 事件定义
const emit = defineEmits(["success"]);

const onSubmit = async () => {
  await formRef.value.validate();
  const isEdit = bannerForm.value.id;
  if (isEdit) {
    await editBannerAPI(bannerForm.value);
    ElMessage.success("编辑成功");
  } else {
    await addBannerAPI(bannerForm.value);
    ElMessage.success("添加成功");
  }
  dialogVisible.value = false;
  emit("success");
};

// 图片上传处理
const sendImage = (url) => {
  bannerForm.value.imgUrl = url;
};

const open = (row) => {
  dialogVisible.value = true;
  bannerForm.value = { ...row };
};

defineExpose({
  open,
});
</script>